package thinker.miracle.business.user.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import thinker.miracle.business.base.BaseController;
import thinker.miracle.commons.Result;
import thinker.miracle.utils.Constants;

/**
 * @author bo.chen
 * 
 * 测试
 *
 */
@Controller
@RequestMapping("/user/file")
public class FileController extends BaseController {

	@ResponseBody
	@RequestMapping(value = "/uploadFile", method = { RequestMethod.POST })
	public void uploadFile(@RequestParam("file") CommonsMultipartFile[] files,
			HttpServletRequest request) {
		Result result = this.getResult();
		FileOutputStream os = null;
		FileInputStream in = null;
		if (files != null) {
			try {
				for (int i = 0; i < files.length; i++) {
					if (!files[i].isEmpty()) {
						String name = new Date().getTime() + "_" + files[i].getOriginalFilename();
						String fileName = Constants.ROOT + name;
						os = new FileOutputStream(fileName);
						in = (FileInputStream) files[i].getInputStream();
						int b = 0;
						while ((b = in.read()) != -1) {
							os.write(b);
						}
						os.flush();
						os.close();
						in.close();
					}
				}
				result.success();
			} catch (Exception e) {
				logger.error("",e);
			}finally{
				try {
					if(os != null)
						os.close();
				} catch (IOException e) {}
				try {
					if(in != null)
						in.close();
				} catch (IOException e) {}
			}
		}
		writeJson(result);
	}
	
	@ResponseBody
	@RequestMapping(value = "/uploadFile1", method = { RequestMethod.POST })
	public void uploadFile1(HttpServletRequest request,HttpServletResponse response) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        Result result = this.getResult();
        result.setMsg("失败");
        try{
	        if(multipartResolver.isMultipart(request)){  
	            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
	            Iterator<String> iter = multiRequest.getFileNames();  
	            while(iter.hasNext()){  
	                MultipartFile file = multiRequest.getFile(iter.next());  
	                if(file != null){  
	                    String name = file.getOriginalFilename();  
	                    if(name.trim() !=""){  
	                        String fileName = new Date().getTime() + "_" + file.getOriginalFilename();  
	                        String path = Constants.ROOT + fileName;  
	                        File localFile = new File(path);  
	                        file.transferTo(localFile);
	                        result.addData("file", fileName);
	                    }
	                }  
	                result.success();
	                result.setMsg("成功");
	            }  
	        }  
        }catch(Exception e){
        	logger.error("",e);
        }
        writeJson(result);
	}
	
	@RequestMapping(value = "/getFileList", method = {RequestMethod.POST,RequestMethod.GET})
	public ModelAndView getFileList(){
		ModelAndView mv = this.getModelAndView();
		List<Map<String,String>> fileList = new ArrayList<Map<String,String>>();
		try{
			String path = Constants.ROOT;
			if(new File(path).exists()){
				File[] files = new File(path).listFiles();
				if(files != null && files.length > 0){
					for(File file : files){
						if(file.exists()){
							Map<String,String> map = new HashMap<String,String>();
							String url = "/"+Constants.ROOT + "/" + file.getName();
							map.put("url", url);
							map.put("name", file.getName());
							fileList.add(map);
						}
					}
				}
			}
		}catch(Exception e){
			logger.error("",e);
		}
		mv.addObject("fileList", fileList);
		mv.setViewName("forward:/list.jsp");
		return mv;
	}
	
	@ResponseBody
	@RequestMapping(value = "/getFile/{filename}.{format}", method = {RequestMethod.POST,RequestMethod.GET})
	public ResponseEntity<byte[]> getFile(@PathVariable("filename") String filename,@PathVariable("format") String format) {
		ResponseEntity<byte[]> responEntity = null;
		try{
			filename = filename + "." + format;
			String path = Constants.ROOT + filename;
	        File file = new File(path);
	        responEntity = this.download(file,null);
		}catch(Exception e){
			logger.error("",e);
		}
        return responEntity;  
	}
}
